import { defineComponent, onMounted, ref } from "vue";
import styles from "./insureForm.module.scss";
import { useStore as useInsureStore } from "@/store/insure";
import AddressCascader from "../AddressCascader/AddressCascader";
import IndentitySelector from "../IndentitySelector/IndentitySelector";
import useSms from "@/hooks/useSms";
import { Toast } from "@nutui/nutui";
import { $orderSingleCreate, $orderSingleRecordScreen } from "@/apis/api";
// import validateInstance from "@/libs/validate/validate";
import InsureConfirm from "../InsureConfirm/InsureConfirm";
import usePay from "@/hooks/usePay";
import { record } from 'rrweb';
import { useStore as useScreenRecordingStore } from '@/store/screenRecording';
import to from "await-to-js";
export default defineComponent({
  setup(props: any, { expose }: any) {
    const pay = usePay();
    const insureStore = useInsureStore();
    const screenRecordingStore = useScreenRecordingStore();

    const sms = useSms();

    const addressCascaderRef = ref(null as any);
    const indentitySelectorRef = ref(null as any);
    const InsureConfirmRef = ref(null as any);

    //下单
    const submit = () => {
      try {
        if (!insureStore.params.applicant.name) {
          throw "请填写投保人姓名!";
        }
        // if (!validateInstance.test(insureStore.params.applicant.id_no, 'idcard')) {
        //   throw "请填写正确的投保人身份证号!";
        // }
        if (!insureStore.params.applicant.address) {
          throw "请选择投保人户口所在地!";
        }
        if (!insureStore.params.applicant.mobile) {
          throw "请填写投保人手机号!";
        }
        if (insureStore.params.applicant.mobile?.length !== 11) {
          throw "投保人手机号格式不正确!";
        }
        if (!insureStore.params.code) {
          throw "请填写投保人手机验证码!";
        }
        insureStore.params.insured.forEach((item: any, index: number) => {
          if (!item.identity) {
            throw `请选择被保人${index + 1}与缴费人关系!`;
          }
          if (!item.name) {
            throw `请输入被保人${index + 1}姓名!`;
          }
          // if (!validateInstance.test(item.id_no, 'idcard')) {
          //   throw `请填写正确的被保人${index + 1}身份证号!`;
          // }
          if (!item.address) {
            throw `请选择被保人${index + 1}户口所在地!`;
          }
          if (!item.mobile) {
            throw `请填写被保人${index + 1}手机号!`;
          }
          if (item?.mobile.length !== 11) {
            throw `被保人${index + 1}手机号格式不正确!`;
          }
        })
      } catch (err: any) {
        Toast.fail(err);
        return;
      }
      InsureConfirmRef.value.open();
    }
    const saveScreenRecord = async (order_no: string) => {
      let params: any = {};
      const event = encodeURIComponent(JSON.stringify(screenRecordingStore.events.order));
      params.order_no = order_no;
      params.screen_record = event;
      params.scene = 'order';
      Toast.loading('记录提交中...', {
        id: 'screenSave',
        duration: 0,
      })
      const [err, res]: any = await to($orderSingleRecordScreen(params));
      if (!err) {
        screenRecordingStore.initEvents('order');
      }
      Toast.hide('screenSave');
    }
    const confirm = () => {
      Toast.loading('投保提交中...', {
        id: 'insure',
        duration: 0,
      })
      $orderSingleCreate({ ...insureStore.params, key: sms.state.key }).then(async (res: any) => {
        InsureConfirmRef.value.close();
        await saveScreenRecord(res?.data?.order_no);
        pay.submit(res?.data?.out_trade_no, res?.data?.order_no);
      }).finally(() => {
        Toast.hide('insure');
      })
    }

    const crateWeb = () => {
      let events: any[] = [];
      record({
        emit(event) {
          // 用任意方式存储 event
          events.push(event);
          screenRecordingStore.addEvents(events, 'order');
        }
      })
    }

    onMounted(() => {
      screenRecordingStore.initEvents('order');
      crateWeb();
    })

    expose({
      submit,
    })
    return () => (
      <>
        <div class={styles.insurer}>
          <div class={styles['insurer-card']}>
            <span class={styles['insurer-title']}>本人信息(缴费人)</span>
            <div class={styles['insurer-signRows']}>
              <div class={styles['signRow']}>
                <span class={styles['signRow-label']}>姓名</span>
                <div class={styles['signRow-value']}>
                  <input placeholder="请输入投保人姓名" v-model={insureStore.form.applicant.name} />
                </div>
              </div>
              <div class={styles['signRow']}>
                <span class={styles['signRow-label']}>证件类型</span>
                <div class={styles['signRow-value']}>
                  <span>身份证</span>
                </div>
              </div>
              <div class={styles['signRow']}>
                <span class={styles['signRow-label']}>证件号</span>
                <div class={styles['signRow-value']}>
                  <input placeholder="请输入投保人证件号" v-model={insureStore.form.applicant.id_no} />
                </div>
              </div>
              <div class={styles['signRow']} onClick={() => {
                addressCascaderRef.value.open({
                  mode: 'applicant',
                  field: 'address',
                  address: insureStore.form.applicant.address,
                })
              }}>
                <span class={styles['signRow-label']}>户口所在地</span>
                <div class={styles['signRow-value']}>
                  <input readonly placeholder="请选择户口所在地" value={insureStore.form.applicant.address.join("")} />
                </div>
                <div class={styles.nabla}></div>
              </div>
              <div class={styles['signRow']}>
                <span class={styles['signRow-label']}>手机号</span>
                <div class={styles['signRow-value']}>
                  <input placeholder="请输入手机号" maxlength={11} v-model={insureStore.form.applicant.mobile} />
                </div>
              </div>
              <div class={styles['signRow']}>
                <span class={styles['signRow-label']}>验证码</span>
                <div class={styles['signRow-value']}>
                  <input placeholder="请输入验证码" v-model={insureStore.form.applicant.code} />
                </div>
                <div class={styles['dynacode-send-btn']} onClick={() => { sms.sendSms(insureStore.form.applicant.mobile) }}>{sms.show_text.value}</div>
              </div>
            </div>
          </div>
        </div>
        {
          insureStore.form.insured.map((item: any, index: number) => (
            <div class={styles['insured-item']}>
              <div class={styles['insured-card']}>
                {
                  index > 0 && (
                    <img class={styles["delete-icon"]} src={require("@/assets/image/close.png")} onClick={() => { insureStore.removeInsured(index) }} />
                  )
                }
                <div class={styles['insured-title']}>
                  <div class={styles.idx}>{index + 1}</div>
                  <span>为谁参保(被保险人)</span>
                </div>
                <div class={styles['insured-signRows']}>
                  <div class={styles['signRow']} onClick={() => { indentitySelectorRef.value.open({ index, identity: item.identity }) }}>
                    <span class={styles['signRow-label']}>与缴费人关系</span>
                    <div class={styles['signRow-value']}>
                      <input readonly placeholder="请选择与缴费人关系" value={item.identity.dict_label} />
                    </div>
                    <div class={styles.nabla}></div>
                  </div>
                  <div class={styles['signRow']}>
                    <span class={styles['signRow-label']}>姓名</span>
                    <div class={styles['signRow-value']}>
                      <input placeholder="请输入投保人姓名" v-model={item.name} />
                    </div>
                  </div>
                  <div class={styles['signRow']}>
                    <span class={styles['signRow-label']}>证件类型</span>
                    <div class={styles['signRow-value']}>
                      <span>身份证</span>
                    </div>
                  </div>
                  <div class={styles['signRow']}>
                    <span class={styles['signRow-label']}>证件号</span>
                    <div class={styles['signRow-value']}>
                      <input placeholder="请输入投保人证件号" v-model={item.id_no} />
                    </div>
                  </div>
                  <div class={styles['signRow']} onClick={() => {
                    addressCascaderRef.value.open({
                      mode: 'insured',
                      index,
                      field: 'address',
                      address: item.address,
                    })
                  }}>
                    <span class={styles['signRow-label']}>户口所在地</span>
                    <div class={styles['signRow-value']}>
                      <input readonly placeholder="请选择户口所在地" value={item.address.join("")} />
                    </div>
                    <div class={styles.nabla}></div>
                  </div>
                  <div class={styles['signRow']}>
                    <span class={styles['signRow-label']}>手机号</span>
                    <div class={styles['signRow-value']}>
                      <input placeholder="请输入手机号" maxlength={11} v-model={item.mobile} />
                    </div>
                  </div>
                </div>
              </div>
            </div>
          ))
        }
        <AddressCascader ref={addressCascaderRef} onChange={
          (e) => {
            switch (e.mode) {
              case 'applicant':
                (insureStore.form.applicant as any)[e.field] = e.address;
                break;
              case 'insured':
                insureStore.form.insured[e.index][e.field] = e.address;
                break;
            }
          }
        } />
        <IndentitySelector ref={indentitySelectorRef} onConfirm={(e) => {
          insureStore.form.insured[e.index].identity = e.identity;
          indentitySelectorRef.value.close();
        }} />
        {/* <InsureConfirm ref={InsureConfirmRef} onConfirm={() => confirm()} /> */}
      </>
    )
  }
})